import re, json
from paramiko import SSHClient


class Command():
    def execute(self):
        raise NotImplementedError()
    

class CryptoProCommand(Command):

    def __init__(self, sshclient: SSHClient):
        self.client = sshclient

    def execute(self):
        steps = []

        user = self.client.exec_command("who | awk '{print $1}' | head -n1")[1].read().decode().strip()
        steps.append(f'Пользователь: {user}')

        tokens = self.client.exec_command(f"sudo -u {user} /opt/cprocsp/bin/amd64/csptest -keyset -enum_cont -verifycontext -uniq | grep -o '|.*' | cut -d '|' -f2")[1].read().decode().split()

        for token in tokens:
            print(token)

            certificate = self.client.exec_command(f"sudo -u {user} /opt/cprocsp/bin/amd64/certmgr -list -cont '{token}'")[1].read().decode()
            while(True):
                certificate = re.search(r'(https?://[^\s]+).crt', certificate)[0]
                print(certificate)
                if certificate is None:
                    break
                certificate = self.client.exec_command(f"sudo -u {user} curl {certificate} | /opt/cprocsp/bin/amd64/certmgr -inst -store mroot -stdin")[1].read().decode()
                
        return { 'steps': steps }
         
